package com.compass.doctor.ui.mine

import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import com.compass.doctor.base.BaseVBActivity
import com.compass.doctor.callback.OnUsefulButtonClick
import com.compass.doctor.databinding.ActivityUsefulCateExpressionsBinding
import com.compass.doctor.dialog.USEFUL_OPT_ADD
import com.compass.doctor.dialog.USEFUL_OPT_ADD_CATE
import com.compass.doctor.dialog.UsefulExpressionsDialog
import com.compass.doctor.ui.mine.adapter.UsefulExpressionsCateAdapter
import com.compass.doctor.ui.mine.viewmodel.UsefulExpressionsViewModel
import com.compass.framework.R
import com.compass.framework.constant.REFRESH_USEFUL_CATE
import com.compass.framework.constant.REFRESH_USEFUL_CATE_COUNT
import com.compass.framework.constant.UsefulTypeOpeEnum
import com.compass.framework.decoration.NormalItemDecoration
import com.compass.framework.dialog.CommonMessageDialog
import com.compass.framework.ext.gone
import com.compass.framework.ext.load
import com.compass.framework.ext.onClick
import com.compass.framework.ext.visible
import com.compass.framework.model.UsefulExpressions
import com.compass.framework.model.UsefulExpressionsCate
import com.compass.framework.utils.LiveDataBus
import com.compass.framework.utils.LogUtil
import com.compass.framework.utils.dpToPx
import com.compass.framework.utils.getStringFromResource
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener
import com.scwang.smart.refresh.layout.listener.OnRefreshListener

/**
 * 常用语分类页面
 */
class UsefulCateExpressionsActivity : BaseVBActivity<ActivityUsefulCateExpressionsBinding>(),
    OnLoadMoreListener,
    OnRefreshListener {

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, UsefulCateExpressionsActivity::class.java)
            context.startActivity(intent)
        }
    }

    private lateinit var mUsefulExpressionsCateAdapter: UsefulExpressionsCateAdapter
    private val mUsefulExpressionsViewModel: UsefulExpressionsViewModel by viewModels()
    private var mPage: Int = 1

    override fun initView(savedInstanceState: Bundle?) {
        mBinding.tvTitleBar.getRightTextView().visible()
        mBinding.tvTitleBar.setRightText("编辑分组")
        mBinding.tvTitleBar.onClick {
            if (mUsefulExpressionsCateAdapter.getmType() == UsefulTypeOpeEnum.LIST) {
                mBinding.tvTitleBar.setRightText("取消编辑")
                mBinding.tvAddExpression.text = "确认删除"
                mUsefulExpressionsCateAdapter.setmType(UsefulTypeOpeEnum.DELETE)
            } else {
                mBinding.tvTitleBar.setRightText("编辑分组")
                mBinding.tvAddExpression.text = "新增分组"
                mUsefulExpressionsCateAdapter.setmType(UsefulTypeOpeEnum.LIST)
            }
        }
        mBinding.tvAddExpression.onClick {

            if (mUsefulExpressionsCateAdapter.getmType() == UsefulTypeOpeEnum.LIST) {
                //显示添加分组的dialog
                UsefulExpressionsDialog.Builder(this, USEFUL_OPT_ADD_CATE, onUsefulButtonClick).show()
            } else {
                if (checkData()) {
                    CommonMessageDialog.Builder(this@UsefulCateExpressionsActivity)
                        .setTitle(getStringFromResource(R.string.dialog_tips_title))
                        .setMessage("是否删除选中的常用语分组？")
                        .setConfirm(getStringFromResource(R.string.default_confirm))
                        .setCancel(getString(R.string.default_cancel))
                        .setonCancelListener {
                            it?.dismiss()
                        }
                        .setonConfirmListener {
                            mUsefulExpressionsViewModel.delUsefulExpressionsCate(
                                mUsefulExpressionsCateAdapter.getChooseCateIds()
                            )
                            it?.dismiss()
                        }.create().show()

                } else {
                    showToast("请先选择常用语分组")
                }
            }
        }

        mUsefulExpressionsViewModel.usefulExpressionsCateListData.observe(this) {
            dismissLoading()
            if (mPage == 1) {
                //第一页数据返回
                mUsefulExpressionsCateAdapter.setData(it)
                mBinding.refreshLayout.finishRefresh()
                mBinding.refreshLayout.setEnableLoadMore(load(it?.size))
                if (it.isNullOrEmpty()) {
                    mBinding.emptyView.visible()
                    mBinding.rvGroup.gone()
                } else {
                    mBinding.emptyView.gone()
                    mBinding.rvGroup.visible()
                }
            } else {
                mBinding.refreshLayout.finishLoadMore()
                if (!it.isNullOrEmpty()) {
                    mUsefulExpressionsCateAdapter.addAll(it)
                } else {
                    mBinding.refreshLayout.setEnableLoadMore(false)
                }
            }
        }

        mUsefulExpressionsViewModel.addUsefulExpressionsCateData.observe(this) {
            dismissLoading()
            if (it) {
                mPage = 1
                getUsefulCateListData()
                //通知上一个页面刷新分类列表数据
                LiveDataBus.get().with(REFRESH_USEFUL_CATE).postValue(REFRESH_USEFUL_CATE)
            }
        }

        mUsefulExpressionsViewModel.delUsefulExpressionsCate.observe(this){
            dismissLoading()
            if (it) {
                mPage = 1
                getUsefulCateListData()
                //通知上一个页面刷新分类列表数据
                LiveDataBus.get().with(REFRESH_USEFUL_CATE).postValue(REFRESH_USEFUL_CATE)
            }
        }

        LiveDataBus.get().with(REFRESH_USEFUL_CATE_COUNT,String::class.java).observe(this){
            mPage = 1
            getUsefulCateListData()
        }
        initRecyclerView()
    }

    /**
     * 校验数据
     */
    private fun checkData(): Boolean {
        val ids = mUsefulExpressionsCateAdapter.getChooseCateIds()
        return ids.isNotEmpty()
    }

    private var onUsefulButtonClick = object : OnUsefulButtonClick {
        override fun onAddButton(content: String, type: Int) {
            super.onAddButton(content, type)
            if (type == USEFUL_OPT_ADD_CATE) {
                //添加常用语分组
                showLoading()
                mUsefulExpressionsViewModel.addUsefulExpressionCate(content)
            }
        }
    }

    private fun initRecyclerView() {
        mUsefulExpressionsCateAdapter = UsefulExpressionsCateAdapter()
        mBinding.refreshLayout.apply {
            setEnableRefresh(true)
            setEnableLoadMore(true)
            setOnRefreshListener(this@UsefulCateExpressionsActivity)
            setOnLoadMoreListener(this@UsefulCateExpressionsActivity)
        }
        mBinding.rvGroup.apply {
            layoutManager = GridLayoutManager(context, 2)
            addItemDecoration(NormalItemDecoration().apply {
                setBounds(
                    top = dpToPx(10),
                    left = dpToPx(5),
                    right = dpToPx(5),
                    bottom = dpToPx(10)
                )
            })
            adapter = mUsefulExpressionsCateAdapter
        }

        mUsefulExpressionsCateAdapter.onItemClickListener = { _, position ->
            val item = mUsefulExpressionsCateAdapter.getItem(position)
            if (mUsefulExpressionsCateAdapter.getmType() == UsefulTypeOpeEnum.LIST) {
                //查看分类下的常用语
                item?.let {
                    item.id?.let { it1 ->
                        item.typeName?.let { it2 ->
                            UsefulExpressionsListActivity.start(
                                this@UsefulCateExpressionsActivity,
                                it1, it2, false
                            )
                        }
                    }
                }
            } else {
                //选中/取消选中
                if (item != null) {
                    val list: MutableList<UsefulExpressionsCate>? =
                        mUsefulExpressionsViewModel.usefulExpressionsCateListData.value;
                    list?.forEachIndexed { index, item ->
                        if (index == position) {
                            item.isSelect = !item.isSelect
                        }
                    }
                    mUsefulExpressionsViewModel.usefulExpressionsCateListData.postValue(list)
                }
            }
        }
    }


    override fun initData() {
        super.initData()
        getUsefulCateListData()
    }

    private fun getUsefulCateListData() {
        showLoading()
        mUsefulExpressionsViewModel.getUsefulExpressionsCateListByCount(mPage)
    }

    override fun onLoadMore(refreshLayout: RefreshLayout) {
        mPage++
        getUsefulCateListData()
    }

    override fun onRefresh(refreshLayout: RefreshLayout) {
        mPage = 1
        getUsefulCateListData()
    }

}